//
//  VRankViewController.m
//  CapriceMusic
//
//  Created by 蒋恩浩 on 16/1/12.
//  Copyright © 2016年 MYX. All rights reserved.
//

#import "VRankViewController.h"
#import "AppDelegate.h"

typedef void(^ReceiveArea)(NSInteger area);

@interface VRankViewController ()<UICollectionViewDataSource, UICollectionViewDelegate, UIPickerViewDataSource, UIPickerViewDelegate>

@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, strong) NSMutableArray *dataSource;
// 分段
@property (nonatomic, strong) UISegmentedControl *segment;
// 第几期
@property (nonatomic, strong) JEHLabel *rankLabel;
// 区域选项
@property (nonatomic, strong) CarouselScrollView *scrollView;
// 接收改变地区的block
@property (nonatomic, copy) ReceiveArea receiveAreaCount;
// 菊花
@property (nonatomic, strong) UIActivityIndicatorView *indicator;
// 期刊日期
@property (nonatomic, strong) NSNumber *date;
// 地区
@property (nonatomic, copy) NSString *areaString;
// 期刊选择视图
@property (nonatomic, strong) UIPickerView *pickerView;
// pickerView选中年
@property (nonatomic, strong) NSNumber *selectedYear;
// 选中期
@property (nonatomic, assign) NSInteger selectedRow;
// 装数据的字典
@property (nonatomic, strong) NSMutableDictionary *dictionary;
// 装key的数组
@property (nonatomic, strong) NSMutableArray *yearsArray;
// 期刊选择确定，取消
@property (nonatomic, strong) UIButton *yesButton;
@property (nonatomic, strong) UIButton *noButton;

@end

@implementation VRankViewController

#pragma mark - lifeCycle
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    self.tabBarController.tabBar.translucent = YES;
    self.tabBarController.tabBar.hidden = YES;
    // 关闭抽屉侧滑效果
    AppDelegate *tempAppDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    [tempAppDelegate.LeftSlideVC setPanEnabled:NO];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.date = @0;
    self.selectedYear = @2016;
    self.selectedRow = 0;
    self.areaString = @"ML";
    self.navigationItem.title = @"V榜";
    self.dataSource = [NSMutableArray arrayWithCapacity:0];
    
    [self createCollectionView];
    [self createSegmentAndTitleView];
    [self getCurrentDataWithURL:kCurrentRankGETURL withArea:@"ML" withOffset:@0];
    [self changeArea];
    [self pullDownUpdate];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    
    self.tabBarController.tabBar.translucent = NO;
    self.tabBarController.tabBar.hidden = NO;
}

#pragma mark - 网络请求，当前打榜周期
- (void)getCurrentDataWithURL:(NSString *)url withArea:(NSString *)area withOffset:(NSNumber *)offset {
    
    [JEHNetWorkTool getWithUrl:url parameter:@{@"date":@"true", @"area":area, @"offset":[NSString stringWithFormat:@"%ld", offset.integerValue], @"size":@"20"} httpHeader:@{@"App-Id":@"10201030", @"Device-Id":@"33d0592ec42230a3ed2fef0ed2febb9a", @"Device-V":@"QW5kcm9pZF80LjIuMl8xMDgwKjE5MjBfMTEwMDA3MDAw"} responseType:ResponseTypeJSON success:^(id result) {
        
        self.rankLabel.text = [NSString stringWithFormat:@"当前打榜周期 第%@期", result[@"no"]];
        [self.rankLabel attributedText:[NSString stringWithFormat:@"第%@期", result[@"no"]] withFont:14 withColor:[UIColor colorWithRed:30 / 255.0 green:195 / 255.0 blue:153 / 255.0 alpha:1.0]];
        NSArray *array = result[@"videos"];
        for (NSDictionary *dictionary in array) {
            
            VRankModel *vRankModel = [[VRankModel alloc] initWithDictionary:dictionary];
            [self.dataSource addObject:vRankModel];
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            
            [self.indicator stopAnimating];
            [self.collectionView reloadData];
        });
    } fail:^(NSError * error) {
        
        
    }];
}

#pragma mark - 网络请求，往期打榜周期
- (void)getPassedDataWithURL:(NSString *)url withArea:(NSString *)area withDatecode:(NSNumber *)datecode {
    
    [JEHNetWorkTool getWithUrl:url parameter:@{@"area":area, @"datecode":[NSString stringWithFormat:@"%ld", datecode.integerValue]} httpHeader:@{@"App-Id":@"10201030", @"Device-Id":@"33d0592ec42230a3ed2fef0ed2febb9a", @"Device-V":@"QW5kcm9pZF80LjIuMl8xMDgwKjE5MjBfMTEwMDA3MDAw"} responseType:ResponseTypeJSON success:^(id result) {
        
        self.rankLabel.text = [NSString stringWithFormat:@"<  %@年第%@期(%@ - %@)  >", result[@"year"], result[@"no"], result[@"beginDateText"], result[@"endDateText"]];
        NSArray *array = result[@"videos"];
        for (NSDictionary *dictionary in array) {
            
            VRankModel *vRankModel = [[VRankModel alloc] initWithDictionary:dictionary];
            [self.dataSource addObject:vRankModel];
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            
            [self.indicator stopAnimating];
            [self.collectionView reloadData];
        });
    } fail:^(NSError *error) {
        
    }];
}

#pragma mark - 网络请求，期刊
- (void)getPeriodDataWithURL:(NSString *)url withArea:(NSString *)area  {
    
    self.dictionary = [NSMutableDictionary dictionaryWithCapacity:0];
    
    [JEHNetWorkTool getWithUrl:kPeriodGETURL parameter:@{@"area":area, @"trend":@"true"} httpHeader:@{@"App-Id":@"10201030", @"Device-Id":@"33d0592ec42230a3ed2fef0ed2febb9a", @"Device-V":@"QW5kcm9pZF80LjIuMl8xMDgwKjE5MjBfMTEwMDA3MDAw"} responseType:ResponseTypeJSON success:^(id result) {
        
        if (result) {

            NSArray *periods = result[@"periods"];
            self.yearsArray = [NSMutableArray arrayWithArray:result[@"years"]];
//            [self.yearsArray sortUsingSelector:@selector(compare:)];
            for (NSNumber *year in self.yearsArray) {

                NSMutableArray *mutableArray = [NSMutableArray arrayWithCapacity:0];
                for (int i = 1; i < periods.count; i++) {
//                    NSLog(@"1 - %@", year);
//                    NSLog(@"2 - %d", [periods[i] objectForKey:@"year"] == year);
                    if ([periods[i] objectForKey:@"year"] == year) {
#warning 在真机上这个条件不能成立
                        [mutableArray addObject:periods[i]];
//                        NSLog(@"%@", mutableArray);
                    }
                    [self.dictionary setObject:mutableArray forKey:year];
                }
            }
            dispatch_async(dispatch_get_main_queue(), ^{
                
                [self.indicator stopAnimating];
                [self pickerViewAppear];
                [self.pickerView reloadAllComponents];
            });
        }
    } fail:^(NSError *error) {
        
    }];
}

#pragma mark - createCollectionView
- (void)createCollectionView {
    
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.itemSize = CGSizeMake(self.view.width - 20, 140);
    layout.minimumLineSpacing = 10;
    layout.sectionInset = UIEdgeInsetsMake(0, 10, 10, 10);
    
    self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 120, self.view.width, self.view.height - 120 - 5) collectionViewLayout:layout];
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    [self.collectionView registerClass:[VRankCollectionViewCell class] forCellWithReuseIdentifier:@"VRankCollectionViewCell"];
    [self.view addSubview:self.collectionView];
}

#pragma mark - collectionView代理方法
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    
    if (self.dataSource.count > 0) {
        
        return self.dataSource.count;
    } else {
        return 0;
    }
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *identifier = @"VRankCollectionViewCell";
    VRankCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath];
    if (self.dataSource.count > 0) {
        
        cell.vRankModel = self.dataSource[indexPath.item];
        cell.count = indexPath.item + 1;
        if (self.segment.selectedSegmentIndex == 0) {
            
            cell.trendLabel.alpha = 1;
        } else {
            cell.trendLabel.alpha = 0;
        }
    }
    cell.layer.masksToBounds = YES;
    cell.layer.cornerRadius = 10;
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    
    DetailViewController *detailVC = [[DetailViewController alloc] init];
    VRankModel *vRankModel = self.dataSource[indexPath.item];
    detailVC.appendingId = vRankModel.ids;
    detailVC.type = @"VIDEO";
    [self.navigationController pushViewController:detailVC animated:YES];
}

#pragma mark -- 下拉刷新
-(void)pullDownUpdate {
    
    __weak typeof(self) weakSelf = self;
    [self.collectionView addHeaderWithCallback:^{
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 *NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            
            [weakSelf.dataSource removeAllObjects];
            if (weakSelf.segment.selectedSegmentIndex == 0) {
                
                [weakSelf getCurrentDataWithURL:kCurrentRankGETURL withArea:weakSelf.areaString withOffset:@0];
            } else {
                [weakSelf getPassedDataWithURL:kPassedRankGETURL withArea:weakSelf.areaString withDatecode:weakSelf.date];
            }
            [weakSelf.collectionView headerEndRefreshing];
        });
    }];
}

#pragma mark - segment及标题
- (void)createSegmentAndTitleView {
    
    // 分段
    self.segment = [[UISegmentedControl alloc] initWithItems:@[@"打榜动态", @"往期榜单"]];
    self.segment.selectedSegmentIndex = 0;
    self.segment.frame = CGRectMake(20, 0, self.view.width - 40, 30);
    self.segment.tintColor = [UIColor colorWithRed:30 / 255.0 green:195 / 255.0 blue:153 / 255.0 alpha:1.0];
    // 设置选中字体颜色(失败)
    //    NSDictionary *dictionary = [NSDictionary dictionaryWithObjectsAndKeys:[UIColor whiteColor], UITextAttributeTextColor, [UIFont systemFontOfSize:14], UITextAttributeFont, nil];
    //    [self.segment setTitleTextAttributes:dictionary forState:UIControlStateNormal];
    [self.segment addTarget:self action:@selector(segmentAction:) forControlEvents:UIControlEventValueChanged];
    [self.view addSubview:self.segment];
    // 地区切换scrollView
    NSArray *titleArray = @[@"日本篇", @"欧美篇", @"内地篇", @"韩国篇", @"港台篇"];
    self.scrollView = [[CarouselScrollView alloc] initWithFrame:CGRectMake(0, 30, self.view.width, 50)];
    [self.scrollView createScrollViewWithArray:titleArray withTitleColor:[UIColor whiteColor]];
    self.scrollView.panGestureRecognizer.delaysTouchesBegan = YES;
    [self.view addSubview:self.scrollView];
    // 排行榜label
    self.rankLabel = [[JEHLabel alloc] initWithFrame:CGRectMake(0, 80, self.view.width, 40) withFont:14 withTextColor:[UIColor whiteColor]];
    self.rankLabel.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:self.rankLabel];
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapClickAction:)];
    [self.rankLabel addGestureRecognizer:tap];
#pragma mark - pickerView
    self.pickerView = [[UIPickerView alloc] initWithFrame:CGRectMake(30, self.view.height, self.view.width - 60, 250)];
    self.pickerView.showsSelectionIndicator = YES;
    self.pickerView.delegate = self;
    self.pickerView.dataSource = self;
    self.pickerView.layer.masksToBounds = YES;
    self.pickerView.layer.cornerRadius = 10;
    self.pickerView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.pickerView];
    // 确定和取消按钮
    self.yesButton = [UIButton buttonWithType:UIButtonTypeSystem];
    self.yesButton.frame = CGRectMake(-(self.view.width - 60) / 2, self.view.height - 70, (self.view.width - 60) / 2 - 1, 50);
    [self.yesButton setTitle:@"确定" forState:UIControlStateNormal];
    [self.yesButton setTitleColor:[UIColor colorWithRed:30 / 255.0 green:195 / 255.0 blue:153 / 255.0 alpha:1.0] forState:UIControlStateNormal];
    [self.yesButton addTarget:self action:@selector(yesButtonAction) forControlEvents:UIControlEventTouchUpInside];
    self.yesButton.layer.masksToBounds = YES;
    self.yesButton.layer.cornerRadius = 10;
    self.yesButton.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.yesButton];
    
    self.noButton = [UIButton buttonWithType:UIButtonTypeSystem];
    self.noButton.frame = CGRectMake(self.view.width + 2, self.view.height - 70, self.yesButton.width, 50);
    [self.noButton setTitle:@"取消" forState:UIControlStateNormal];
    [self.noButton setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    [self.noButton addTarget:self action:@selector(noButtonAction) forControlEvents:UIControlEventTouchUpInside];
    self.noButton.layer.masksToBounds = YES;
    self.noButton.layer.cornerRadius = 10;
    self.noButton.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.noButton];
}

#pragma mark - 确定取消点击事件
- (void)yesButtonAction {
    
    [self noButtonAction];
    [self.dataSource removeAllObjects];
    [self.collectionView reloadData];
    [self.indicator startAnimating];
    [self getPassedDataWithURL:kPassedRankGETURL withArea:self.areaString withDatecode:self.date];
}

- (void)noButtonAction {
    
    self.collectionView.userInteractionEnabled = YES;
    [UIView animateWithDuration:0.5 animations:^{
        
        self.pickerView.frame = CGRectMake(30, self.view.height, self.view.width - 60, 250);
    }];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.4 *NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        [UIView animateWithDuration:0.5 animations:^{
            
            self.yesButton.frame = CGRectMake(-(self.view.width - 60) / 2, self.view.height - 70, (self.view.width - 60) / 2 - 1, 50);
            self.noButton.frame = CGRectMake(self.view.width + 2, self.view.height - 70, self.yesButton.width, 50);
        }];
    });
}

#pragma mark - 往期点击手势
- (void)tapClickAction:(UITapGestureRecognizer *)tap {
    
    self.collectionView.userInteractionEnabled = NO;
    [self getPeriodDataWithURL:kPeriodGETURL withArea:self.areaString];
    [self.indicator startAnimating];
}

#pragma mark - pickerView出现方法
- (void)pickerViewAppear {
    
    [UIView animateWithDuration:0.5 animations:^{
        
        self.pickerView.frame = CGRectMake(30, self.view.height - 250 - 80, self.view.width - 60, 250);
    }];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.4 *NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        [UIView animateWithDuration:0.5 animations:^{
            self.yesButton.frame = CGRectMake(30, self.view.height - 70, (self.view.width - 60) / 2, 50);
            self.noButton.frame = CGRectMake(self.yesButton.width + 30 + 2, self.view.height - 70, self.yesButton.width, 50);
        }];
    });
}

#pragma mark - segment点击事件
- (void)segmentAction:(UISegmentedControl *)segment {
    
    [self.dataSource removeAllObjects];
    [self.collectionView reloadData];
    if (segment.selectedSegmentIndex == 0) {
        
        [self.dataSource removeAllObjects];
        [self.collectionView reloadData];
        [self.indicator startAnimating];
        [self getCurrentDataWithURL:kCurrentRankGETURL withArea:@"ML" withOffset:0];
        self.rankLabel.userInteractionEnabled = NO;
    } else {
        [self.dataSource removeAllObjects];
        [self.collectionView reloadData];
        [self.indicator startAnimating];
        [self getPassedDataWithURL:kPassedRankGETURL withArea:@"ML" withDatecode:0];
        self.rankLabel.userInteractionEnabled = YES;
    }
}

#pragma mark - 改变地区(添加菊花)
- (void)changeArea {
    
    // 菊花
    self.indicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
    self.indicator.center = self.view.center;
    [self.indicator startAnimating];
    [self.view addSubview:self.indicator];
    // 改变地区
    __weak typeof(self) weakSelf = self;
    self.receiveAreaCount = ^(NSInteger area) {
        
        [weakSelf.indicator startAnimating];
        [weakSelf.dataSource removeAllObjects];
        [weakSelf.collectionView reloadData];
        // 判断地区
        switch (area) {
            case 5:
                weakSelf.areaString = @"JP";
                break;
            case 6:
                weakSelf.areaString = @"US";
                break;
            case 7:
                weakSelf.areaString = @"ML";
                break;
            case 8:
                weakSelf.areaString = @"KR";
                break;
            case 9:
                weakSelf.areaString = @"HT";
                break;
                
            default:
                break;
        }
        if (self.segment.selectedSegmentIndex == 0) {
            
            [weakSelf getCurrentDataWithURL:kCurrentRankGETURL withArea:weakSelf.areaString withOffset:@0];
        } else {
            [weakSelf getPassedDataWithURL:kPassedRankGETURL withArea:weakSelf.areaString withDatecode:weakSelf.date];
        }
    };
    self.scrollView.changeAreaBlock = self.receiveAreaCount;
}

#pragma mark - pickView代理方法
// 返回列数
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
    
    if (self.dictionary.count > 0) {
        
        return 2;
    }
    return 0;
}

// 每一列行数
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
    
    if (component == 0) {
        
        return self.yearsArray.count;
    } else {
        return [[self.dictionary objectForKey:self.selectedYear] count];
    }
}

// 指定列的行显示的内容(自定义视图了，这个没用了)
//- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
//
//    if (component == 0) {
//        
//        return [NSString stringWithFormat:@"%@", self.yearsArray[row]];
//    } else {
//        return [NSString stringWithFormat:@"第%@期(%@ - %@)", [[[self.dictionary objectForKey:self.selectedYear] objectAtIndex:row] objectForKey:@"no"], [[[self.dictionary objectForKey:self.selectedYear] objectAtIndex:row] objectForKey:@"beginDateText"], [[[self.dictionary objectForKey:self.selectedYear] objectAtIndex:row] objectForKey:@"endDateText"]];
//    }
//}

// 选中时走
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
    
    if (component == 0) {
        
        self.selectedYear = self.yearsArray[row];
        [self.pickerView reloadComponent:1];
        self.date = [[[self.dictionary objectForKey:self.selectedYear] objectAtIndex:self.selectedRow] objectForKey:@"dateCode"];
    } else {
        self.selectedRow = row;
        self.date = [[[self.dictionary objectForKey:self.selectedYear] objectAtIndex:row] objectForKey:@"dateCode"];
    }
}

// 列宽度
- (CGFloat)pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component {
    
    if (component == 0) {
        
        return (self.pickerView.width - 20) / 3;
    } else {
        return (self.pickerView.width - 20) / 3 * 2;
    }
}

// 自定义pickerView视图
- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view {
    
    UILabel *pickerLabel = (UILabel *)view;
    if (!pickerLabel) {
        
        pickerLabel = [[UILabel alloc] init];
        pickerLabel.textAlignment = NSTextAlignmentCenter;
    }
    if (component == 0) {

//        pickerLabel.font = [UIFont systemFontOfSize:22];
        pickerLabel.text = [NSString stringWithFormat:@"%@", self.yearsArray[row]];
    } else {
//        pickerLabel.font = [UIFont systemFontOfSize:20];
        pickerLabel.text = [NSString stringWithFormat:@"第%@期(%@ - %@)", [[[self.dictionary objectForKey:self.selectedYear] objectAtIndex:row] objectForKey:@"no"], [[[self.dictionary objectForKey:self.selectedYear] objectAtIndex:row] objectForKey:@"beginDateText"], [[[self.dictionary objectForKey:self.selectedYear] objectAtIndex:row] objectForKey:@"endDateText"]];
    }
    [pickerLabel sizeToFit];
    return pickerLabel;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
